<!--
 * @Description  :
 * @Autor        : guoxi
 * @Date         : 2022-06-16 10:16:50
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-11-17 11:52:51
 * @FilePath     : \rpms\src\views\project\check\detail\index.vue
-->
<template>
  <div>
    <el-card>
      <div class="card-wrap">
        <el-page-header content="添加验收信息" @back="handleBack" />
        <div>
          <template v-if="!isApproval">
            <el-button @click="goBack">取消</el-button>
            <el-button
              v-if="!route.query.instanceId"
              type="primary"
              :loading="model.saveLoading"
              @click="handleSave"
              >保存</el-button
            >
            <el-button
              type="primary"
              :loading="model.saveLoading"
              @click="handleSubmit('start')"
              >提交</el-button
            >
          </template>

          <!-- <template v-if="isApproval">
            <template v-if="!model.isNoReject">
              <el-button
                type="primary"
                :loading="model.saveLoading"
                @click="handleReject"
                >驳回</el-button
              >
            </template>
            <el-button
              type="primary"
              :loading="model.saveLoading"
              @click="handleSubmit('agree')"
              >通过</el-button
            >
          </template> -->
        </div>
      </div>
    </el-card>
    <br />
    <el-form
      :model="model.formData"
      ref="formRef"
      @submit.prevent
      :rules="formRules"
      label-width="140px"
    >
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目基本信息</span>
            <div v-if="show1" @click="show1 = !show1" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show1 = !show1" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show1">
          <BasicsInfo :projectInfo="projectInfo" />
        </div>
      </el-card>
      <br />

      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目目标及考核指标</span>
            <div v-if="show2" @click="show2 = !show2" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show2 = !show2" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show2">
          <check-table-list
            :data="model.tableData"
            :isEdit="route.query.source === 'back' || !route.query.instanceId"
          ></check-table-list>
        </div>
      </el-card>
      <br />
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目验收报告</span>
            <div v-if="show3" @click="show3 = !show3" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show3 = !show3" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show3">
          <el-row>
            <el-col>
              <el-form-item label="项目验收报告">
                <!-- <el-upload
                  name="uploadFile"
                  multiple
                  :accept="acceptTypes"
                  :action="uploadComUrl"
                  :headers="uploadHeaders"
                  :on-success="handleReviewSuccess"
                  :on-remove="handleReviewRemove"
                  :on-error="handleError"
                  :file-list="model.reviewDefaultFileList"
                  :before-upload="beforeAvatarUpload"
                  :on-preview="handlePreview"
                >
                  <el-button :disabled="isDisabled" size="small" type="primary"
                    >上传</el-button
                  >
                  <el-link
                    style="margin-left: 16px"
                    type="primary"
                    @click="
                      postDownload('研发项目验收报告（简化版）-模版.docx')
                    "
                    >研发项目验收报告（简化版）-模版.docx
                  </el-link>

                  <template #tip>
                    <div class="el-upload__tip">
                      支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                    </div>
                  </template>
                </el-upload> -->
                <ecm-upload
                  :disabled="isDisabled"
                  :files="model.reviewDefaultFileList"
                  :docid="model.docid"
                  @setFile="handleReviewSuccess"
                >
                  <template #temp>
                    <el-link
                      style="margin-left: 16px"
                      type="primary"
                      @click="
                        postDownload('研发项目验收报告（简化版）-模版.docx')
                      "
                      >研发项目验收报告（简化版）-模版.docx
                    </el-link>
                  </template>
                </ecm-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item
                label="项目经费决算报告"
                prop="finaReportAttachmentArr"
              >
                <!-- <el-upload name="uploadFile" multiple :accept="acceptTypes" :action="uploadComUrl"
                  :headers="uploadHeaders" :on-success="handleApprovalSuccess" :on-remove="handleApprovalRemove"
                  :on-error="handleError" :file-list="model.approvalDefaultFileList" :before-upload="beforeAvatarUpload"
                  :on-preview="handlePreview">
                  <el-button :disabled="isDisabled" size="small" type="primary">上传</el-button>
                  <el-link style="margin-left: 16px" type="primary" @click="
                    postDownload('研发项目经费决算报告（简化版）-模版.docx')
                    ">研发项目经费决算报告（简化版）-模版.docx
                  </el-link>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                    </div>
                  </template>
                </el-upload> -->
                <ecm-upload
                  :disabled="isDisabled"
                  :files="model.approvalDefaultFileList"
                  :docid="model.docid"
                  @setFile="handleApprovalSuccess"
                >
                  <template #temp>
                    <el-link
                      style="margin-left: 16px"
                      type="primary"
                      @click="
                        postDownload('研发项目经费决算报告（简化版）-模版.docx')
                      "
                      >研发项目经费决算报告（简化版）-模版.docx
                    </el-link>
                  </template>
                </ecm-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <br />
      <el-card v-if="route.query.instanceId">
        <template #header>
          <div class="card-box-header">
            <span> 专家评审意见</span>
            <div v-if="show9" @click="show9 = !show9" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show9 = !show9" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show9">
          <ExperReviewtList :projectInfo="projectInfo" />
          <BuildApproval :projectInfo="projectInfo" class="mg-top" />
        </div>
      </el-card>
      <br />
      <el-card v-if="route.query.instanceId">
        <template #header>
          <div class="card-box-header">
            <span> 流程状态</span>
            <div v-if="show4" @click="show5 = !show5" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show5 = !show5" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-if="steps && steps.length">
          <el-collapse-transition>
            <status-info
              :currentStep="currentStep"
              :steps="steps"
              :isSkip="isSkipYs"
            />
          </el-collapse-transition>
        </div>
      </el-card>
      <br />
      <el-card v-if="route.query.instanceId">
        <template #header>
          <div class="card-box-header">
            <span> 流转记录</span>
            <div v-if="show4" @click="show6 = !show6" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show6 = !show6" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show6">
          <el-collapse-transition>
            <approval-info :activities="approveRecord" />
          </el-collapse-transition>
        </div>
      </el-card>
    </el-form>
  </div>

  <approveDialog
    v-if="approveDialogVisiable"
    :nodeId="nodeId"
    :flowType="model.flowType"
    @cancel="cancel"
    @sure="sureSubmit"
  ></approveDialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import ExperReviewtList from "/@/views/approval/detail/components/ExperReviewtList.vue";
import BuildApproval from "/@/views/approval/detail/components/BuildApproval.vue";
import BasicsInfo from "../../detail/components/BasicsInfo.vue";
import approveDialog from "/@/components/approveDialog/index.vue";
import StatusInfo from "/@/components/StatusInfo/index.vue";
import ApprovalInfo from "/@/components/ApprovalInfo/index.vue";
import { flowStatusObj } from "/@/components/StatusInfo/type";
import {
  getProjectInfo,
  updateAacceptance,
  getAacceptanceById,
  submitStage,
  flowStart,
  getApproveHistory,
  flowSubmit
} from "/@/api/project";
import { cloneDeep } from "lodash-es";
import NotifMessage from "/@/utils/message/notification";
import { flowTypeCode } from "../../create/types";
import { storageLocal } from "/@/utils/storage";
import CheckTableList from "../component/table-list.vue";
import EcmUpload from "/@/components/ecmUpload/index.vue";
const router = useRouter();
const route = useRoute();
const formRef = ref<HTMLFormElement | null>(null) as any;
let show1 = ref<boolean>(true);
let show2 = ref<boolean>(true);
let show3 = ref<boolean>(true);
let show4 = ref<boolean>(true);
let show5 = ref<boolean>(true);
let show6 = ref<boolean>(true);
let show9 = ref<boolean>(true);
let approveDialogVisiable = ref<boolean>(false); // 点击提交弹窗，选择下一步审批人
let rejectDialogVisiable = ref<boolean>(false); // 点击驳回弹窗，选择下一步审批人
const isApproval =
  route.query.mode === "approval" || route.query.mode === "look" ? true : false;
const isDisabled = ref<boolean>(false);
const nodeId = route.query.nodeId ? route.query.nodeId : "ACT_010";
const isSkipYs = route.query.isSkipYs;
const currentStep = ref(null);
const steps = ref([]);
const approveRecord = ref([]);

const formRules = ref({
  // oaApproveNum: [
  //   { required: true, message: "请输入OA审批单编号", trigger: "change" }
  // ],
  // oaApproveOption: [
  //   { required: true, message: "请选择审批意见", trigger: "change" }
  // ],
  // finaReportAttachmentArr: [{ required: true, message: "请上传附件", trigger: "change" }]
});
const model = reactive({
  docid: window["ecmDocType"].project,
  flowType: "2001",
  approveHandlerId: null,
  approvalStep: "start",
  dialogType: "approval",
  saveLoading: false,
  scientifics: [],
  scientificList: [],
  scientificTableList: [],
  total: 0,
  index: 0,
  checkId: "", //验收评审,验收审批 id
  opinions3: [
    { key: "0", label: "通过验收" },
    { key: "1", label: "重新评审" },
    { key: "2", label: "不通过验收" }
  ],
  types2: [
    { dicCode: "1", dicValue: "专利" },
    { dicCode: "2", dicValue: "论文" },
    { dicCode: "3", dicValue: "专著" },
    { dicCode: "4", dicValue: "标准" },
    { dicCode: "5", dicValue: "科技奖励" },
    { dicCode: "6", dicValue: "科技制度建设" },
    { dicCode: "7", dicValue: "软件著作权" },
    { dicCode: "8", dicValue: "其他" }
  ],

  dialogFormVisible: false,
  dones: [
    { key: "0", label: "是" },
    { key: "1", label: "否" }
  ],
  opinions2: [
    { key: "0", label: "同意" },
    { key: "1", label: "不同意" }
  ],
  opinions: [
    { key: "0", label: "同意通过验收" },
    { key: "1", label: "不同意通过验收" },
    { key: "0", label: "重新审议" }
  ],
  tableData: [],
  defaultFileList: [],
  reviewDefaultFileList: [],
  approvalDefaultFileList: [],
  formData: {
    projectId: "",
    projectReviewTime: "",
    projectReviewLocation: "",
    // reviewExpert: [],
    projectReviewOption: "",
    accReportAttachmentArr: [],
    remark: "",
    oaApproveNum: "",
    oaApproveOption: "",
    finaReportAttachmentArr: [],
    projectTargetList: []
  }
});

const postDownload = fileName => {
  window.open(`${location.origin}${location.pathname}/${fileName}`);
};

//发起流程
const flowStartData = reactive({
  formBaseInfo: {
    billName: "",
    projectName: "",
    projectManageId: route.query.id,
    id: route.query.id,
    flowStartAttachmentArr: []
  },
  flowFormData: {
    businessId: route.query.id,
    flowTypeCode: "",
    nodeId: route.query.nodeId,
    projectManageId: route.query.id,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "4", //立项：2，变更：20，验收：4
    flowType: "",
    assignee: null,
    opinion: ""
  }
});

const handleReviewSuccess = res => {
  // if (res.code === 200) {
  //   nextTick(() => {
  model.reviewDefaultFileList = res.file;
  model.formData.accReportAttachmentArr = res.file;
  //   });
  // }
};
const handleApprovalSuccess = res => {
  // if (res.code === 200) {
  //   nextTick(() => {
  model.approvalDefaultFileList = res.file;
  model.formData.finaReportAttachmentArr = res.file;
  //   });
  // }
};

const handleBack = () => {
  router.replace("/project/check");
};

let projectInfo = ref(null);

const goBack = (): void => {
  router.push("/project/check");
};

// 点击提交，校验通过后，弹窗：选择下一节点处理人
const handleSubmit = async type => {
  model.approvalStep = type;
  model.dialogType = "approval";
  model.saveLoading = true;
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  model.saveLoading = false;
  if (isValid) {
    approveDialogVisiable.value = true;
  }
};
const flowPassData = reactive({
  formBaseInfo: {
    id: route.query.id,
    acceptUsers: null
  },
  flowFormData: {
    approvalComments: "",
    approvalResult: "",
    businessId: route.query.id,
    flowId: route.query.flowId,
    flowTypeCode: "",
    instanceId: route.query.instanceId,
    nodeId: route.query.nodeId,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "4",
    flowType: "",
    nodeId: route.query.nodeId,
    procInstId: route.query.instanceId,
    taskId: route.query.taskId,
    opinion: "",
    assignee: null,
    isChargehand: "1", //1：向下提交到下一步：0：回退到某一步
    specialReject: "0"
  },
  tmpStorage: {
    nodeId: route.query.nodeId,
    flowId: route.query.flowId,
    taskId: route.query.taskId,
    handlerId: null,
    valueJson: ""
  }
});

const flowPassSubmit = async params => {
  flowPassData.flowFormData.approvalComments = params.remark;
  flowPassData.flowFormData.approvalResult = "1"; //同意：1，不同意：0
  flowPassData.flowFormData.remarks = params.remark;
  flowPassData.flowFormData.flowTypeCode = model.flowType;
  flowPassData.formSubMap.opinion = ``;
  flowPassData.tmpStorage.valueJson = JSON.stringify(flowPassData.formSubMap);
  const info = storageLocal.getItem("rdms-info");
  const userId = info?.userId;
  flowPassData.tmpStorage.handlerId = userId;
  flowPassData.formBaseInfo.acceptUsers = params?.handlederId?.id || userId;
  flowPassData.formSubMap.assignee = params?.handlederId?.id || userId;
  flowPassData.formSubMap.isChargehand = "1";
  flowPassData.formSubMap.flowType = model.flowType;
  const { code, message } = await flowSubmit(flowPassData);
  if (code === 200) {
    NotifMessage.success(message);
    router.push("/approval/todo");
  } else {
    NotifMessage.error(message);
  }
};

const sureSubmit = async params => {
  approveDialogVisiable.value = false;
  model.saveLoading = false;
  const flag = await handleSave(false);
  if (!flag) {
    model.saveLoading = true;
    if (route.query.instanceId) {
      flowPassSubmit(params);
    } else {
      flowSumbitStart(params);
    }
  }
};

// 点击弹窗的确定后，保存、提交，单据往下流转
const flowSumbitStart = async params => {
  const { code, message } = await submitStage(route.query.id);
  model.saveLoading = false;
  if (code === 200) {
    startProcess(params);
  } else {
    NotifMessage.error(message);
  }
};

// 流程发起
const startProcess = async params => {
  flowStartData.flowFormData.remarks = params.remark;
  flowStartData.formSubMap.assignee = params?.handlederId?.id;
  flowStartData.formSubMap.opinion = `备注:${params.remark}`;
  model.saveLoading = true;
  const { code, message } = await flowStart(flowStartData);
  if (code === 200) {
    NotifMessage.success(message);
    goBack();
  } else {
    NotifMessage.error(message);
  }
};

const handleSave = async (flag = true): Promise<any> => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  try {
    if (isValid) {
      const copyFormData = cloneDeep(model.formData);
      copyFormData.projectId = +route.query.id;
      // copyFormData.reviewExpert = JSON.stringify(
      //   authorSelectTable.value.participantList
      // );

      // copyFormData.finaReportAttachmentArr = JSON.stringify(copyFormData.finaReportAttachmentArr);
      // copyFormData.accReportAttachmentArr = JSON.stringify(
      //   copyFormData.accReportAttachmentArr
      // );
      copyFormData.id = model.checkId;
      copyFormData.projectTargetList = model.tableData;
      copyFormData.projectTargetList.map(el => {
        if (el.scientificAchv) {
          el.scientificAchv = el.scientificAchv.join(",");
        }
      });
      model.saveLoading = true;
      const { code, message } = await updateAacceptance(copyFormData);
      model.saveLoading = false;
      if (code === 200) {
        if (flag) {
          NotifMessage.success(message);
          goBack();
          return true;
        } else {
          return false;
        }
      }
    } else {
      NotifMessage.warning("请补充必填信息后，再次操作！");
      return true;
    }
  } catch (err) {
    console.error(err);
    return true;
  }
};

//查询项目详情
const initProjectInfo = async () => {
  try {
    const queryId = route.query?.id ?? "";
    const { code, data } = queryId && (await getProjectInfo({ id: queryId }));
    if (code === 200) {
      console.log(data, "data");
      projectInfo.value = data;
      projectInfo.value.projectManageId = +route.query.id;
      projectInfo.value.reviewStageCode = 4;
      const emyp = data.approveTypeMaxCode + "," + data.approveTypeMinCode;
      model.flowType = flowTypeCode[emyp];

      flowStartData.formBaseInfo.billName =
        data.projectName + "-项目验收-审批流程";
      flowStartData.formBaseInfo.projectName = data.projectName;
      flowStartData.flowFormData.flowTypeCode = model.flowType;
      flowStartData.formSubMap.flowType = model.flowType;

      if (model.flowType) {
        getStep();
      }
    }
    const res = await getAacceptanceById(queryId);
    if (res.code === 200 && res.data != null) {
      res.data.projectTargetList.map(el => {
        if (el.scientificAchv) {
          const strArr = el.scientificAchv.split(",");
          el.scientificAchv = strArr.map(str => +str);
        }
        if (el.scientificAchvs) {
          el.scientificAchvs.map(obj => {
            if (obj.kyAttachmentArr == null) {
              obj.kyAttachmentArr = [];
            } else {
              obj.kyAttachmentArr.map(file => {
                file["name"] = file.fileName;
              });
            }
          });
        }
      });
      model.checkId = res.data.id;
      model.tableData = res.data.projectTargetList;
      if (res.data.finaReportAttachmentArr) {
        model.formData.finaReportAttachmentArr =
          res.data.finaReportAttachmentArr;
        // model.formData.finaReportAttachmentArr = JSON.parse(res.data.finaReportAttachmentArr);
        model.approvalDefaultFileList = res.data.finaReportAttachmentArr;
        model.approvalDefaultFileList.map(el => {
          el["name"] = el.fileName;
        });
      }

      if (res.data.accReportAttachmentArr) {
        model.formData.accReportAttachmentArr = res.data.accReportAttachmentArr;
        model.reviewDefaultFileList = res.data.accReportAttachmentArr;
        model.reviewDefaultFileList.map(el => {
          el["name"] = el.fileName;
        });
      }
      //   if (res.data.oaApproveNum) {
      //     model.formData = res.data;
      //     res.data.reviewExpert == null
      //       ? (res.data.reviewExpert = [])
      //       : (model.formData.reviewExpert = JSON.parse(res.data.reviewExpert));

      //   }
    }
  } catch (err) {
    console.log(err);
  }
};

//查询流程审批记录
const getApproveHistoryList = async () => {
  const instanceId = route.query.instanceId;
  if (instanceId) {
    const { code, data } = await getApproveHistory(instanceId);
    if (code === 200) {
      approveRecord.value = data;
    }
  }
};

//获取流程转态
const getStep = () => {
  const nodeId = route.query.nodeId ? route.query.nodeId : "ACT_010";
  steps.value = flowStatusObj[model.flowType];
  if (steps.value && steps.value.length) {
    steps.value.forEach((item, index) => {
      if (item.nodeId === nodeId) {
        currentStep.value = Number(index);
      }
    });
  }
};

const cancel = async () => {
  rejectDialogVisiable.value = false;
  approveDialogVisiable.value = false;
  model.saveLoading = false;
};
if (nodeId === "ACT_010" && route.query.mode === "approval") {
  //提交审核驳回到第一步
  isDisabled.value = false;
} else {
  if (route.query.mode === "approval" || route.query.mode === "look") {
    isDisabled.value = true;
  }
}
initProjectInfo();
getApproveHistoryList();
</script>

<style lang="scss" scoped>
.empt-content {
  height: calc(100vh - 200px);
  width: 100%;
}

.card-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-box-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-btn {
    font-size: 14px;
    cursor: pointer;
  }
}
</style>
